package com.liangjiange.netty.protocol.client;

import java.util.Date;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import com.alibaba.fastjson.JSON;
import com.liangjiange.model.Position;
import com.liangjiange.netty.protocol.struct.Header;
import com.liangjiange.netty.protocol.struct.NettyMessage;
import com.liangjiange.netty.protocol.util.MessageType;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelPipeline;

/**
 * @author Lilinfeng
 * @date 2014年3月15日
 * @version 1.0
 */
public class LogicReqHandler extends ChannelInboundHandlerAdapter {
	
	private volatile ScheduledFuture<?> sentPosition;

	/**
	 * Calls {@link ChannelHandlerContext#fireChannelActive()} to forward to the
	 * next {@link ChannelHandler} in the {@link ChannelPipeline}.
	 * 
	 * Sub-classes may override this method to change behavior.
	 */
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		//ctx.writeAndFlush(JSON.toJSONString(buildLoginReq()));
	}

	/**
	 * Calls {@link ChannelHandlerContext#fireChannelRead(Object)} to forward to
	 * the next {@link ChannelHandler} in the {@link ChannelPipeline}.
	 * 
	 * Sub-classes may override this method to change behavior.
	 */
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		NettyMessage message = JSON.parseObject((String) msg, NettyMessage.class);
		if (message.getHeader() != null
				&& message.getHeader().getType() == MessageType.LOGIN_RESP.value()) {
		sentPosition = ctx.executor().scheduleAtFixedRate(
				new LogicReqHandler.SendPositionTask(ctx), 0, 40000, TimeUnit.MILLISECONDS);
		}
	}

	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		ctx.fireExceptionCaught(cause);
	}
	
	private class SendPositionTask implements Runnable {
		private final ChannelHandlerContext ctx;

		public SendPositionTask(final ChannelHandlerContext ctx) {
			this.ctx = ctx;
		}

		@Override
		public void run() {
			NettyMessage sendPosition = buildLoginReq();
			System.out.println("Client send position message to server : ---> " + sendPosition);
			ctx.writeAndFlush(JSON.toJSONString(sendPosition));
		}

		private NettyMessage buildLoginReq() {
			NettyMessage message = new NettyMessage();
			Header header = new Header();
			header.setType(MessageType.LOGIC_REQ.value());
			message.setHeader(header);
			Position position = new Position();
			position.setDeviceId("123456");
			position.setLongitude(120.0);
			position.setLatitude(30.1);
			position.setDeviceTime(new Date());
			message.setBody(position);
			return message;
		}
	}
	
}
